﻿/// <reference path="../vsdoc/jquery-1.8.3-vsdoc.js" />

/*
** settings for AutoComplete
**
** Every ReadController implments AutoComplete action (which returns unfiltered list)
**
** To provide custom filtering override "OnAutoCompleteList()" see CodeListController for an example
*/

/* AutoComplete */
asyncHandlersForEach.push(ExtendInputWithAutocomplete);
function ExtendInputWithAutocomplete()
{
    $("INPUT.autoComplete").each(function (e)
    {
        var href = $(this).data("autocompleteurl");
        $(this).autocomplete
        ({
            source: function (request, response)
            {
                $.ajax({ url: href
                , type: "GET"
                , dataType: "text"
                , contentType: "application/json"
                , data:
                {
                    MaxRowsPerPage: 7,
                    term: request.term,
                    dt: "" + new Date().getTime()
                },
                    success: function (data)
                    {
                        dataSource = $.parseJSON(data);
                        response($.map(dataSource.options, function (item)
                        {
                            return { label: item.label, value: item.value };
                        }));
                    }
                });
            },
            minLength: 1,
            select: function (ev, ui)
            {
                ev.preventDefault();
                $(this).unbind('keypress');
                $(this).attr("value", ui.item.label);
                $(this).nextAll("INPUT:hidden:first").attr("value", ui.item.value);
            },
            focus: function () { return false; },
            open: function () { },
            close: function () { },
        });
    });
}

$(document).on('change', 'INPUT.autoComplete', function (e)
{
    if ($(this).val() == "")
    {
        $(this).nextAll("INPUT:hidden:first").attr("value", "");
    }
});
